/* eslint-disable */
import { logout} from '@/api/user'
import {GetCurrentUserInfo} from "@/api/api";
import {getToken, removeToken, setToken} from '@/utils/auth'
import router, {resetRouter} from '@/router'

const state = {
  token: getToken(),
  userName: '',
  nickName:'',
  remark:'',// 备注？
  avatar: '',
  roles: [],
  admin:false,
  userId:''
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },

  SET_USERNAME: (state, name) => {
    state.userName = name
  },
  SET_NICKNAME:(state,name)=>{
    state.nickName = name ;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_ADMIN:(state,admin)=>{
    state.admin=admin;
  },
  SET_USERID:(state,userId)=>{
    state.userId = userId;
  }

}

const actions = {
  // user login
  login({commit}, userInfo) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', userInfo.token)
      setToken(userInfo.token)
      resolve()
    }).catch(error => {
      // eslint-disable-next-line no-undef
      reject(error)
    })
  },
  // get user info
  getInfo({commit, state}) {
    return new Promise((resolve, reject) => {
      GetCurrentUserInfo(state.token).then(response => {
        let {data} = response

        if (!data) {
          reject('Verification failed, please Login again.')
        }

        // console.log('after get current user info',data)
        let {roles, userName,nickName,remark, avatar, introduction,admin,userId} = data.user;

        // roles must be a non-empty array
        // custom roles
        roles = [admin?'admin':'coach']
        data.roles = roles;
        data.user.roles = roles;
        console.log('roles',roles)
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }

        commit('SET_ROLES', roles)
        commit('SET_USERNAME', userName)
        commit('SET_NICKNAME', nickName)
        commit('SET_AVATAR', avatar)
        commit('SET_ADMIN', admin);
        commit('SET_USERID', userId);
        console.log('get info',data)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({commit, state, dispatch}) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resetRouter()

      // reset visited views and cached views
      // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
      dispatch('tagsView/delAllViews', null, {root: true})

      resolve()
      // logout(state.token).then(() => {
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },

  // remove token
  resetToken({commit}) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({commit, dispatch}, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const {roles} = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, {root: true})
    // dynamically add accessible routes

    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, {root: true})
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
